package com.example.su_shi_tan_core.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

//    private static final String HEXDIGITS[] = {"0", "1", "2", "3", "4", "5",
//            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    public static String getMD5Str(String sString) {

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (md5 != null) {
            md5.update(sString.getBytes());
        }
        byte[] abResult = new byte[0];
        if (md5 != null) {
            abResult = md5.digest();
        }

        return convertByte2Hex(abResult);

//        byte[] digest = null;
//        try {
//            MessageDigest md5 = MessageDigest.getInstance("md5");
//            digest = md5.digest(str.getBytes("utf-8"));
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        //16是表示转换为16进制数
//        String md5Str = new BigInteger(1, digest).toString(16);
//        return md5Str;
    }

    public static String md5Hex(String str) {

        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest = md5.digest(str.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        String md5Str = new BigInteger(1, digest).toString(16);
        return md5Str;
    }

    public static String convertByte2Hex(byte[] abValue) {
        if (abValue == null) {
            return null;
        }

        String sTemp;
        StringBuffer sbHex = new StringBuffer();

        for (byte b : abValue) {
            sTemp = Integer.toHexString(b & 0XFF);
            if (1 == sTemp.length()) {
                sbHex.append('0').append(sTemp);
            } else {
                sbHex.append(sTemp);
            }
        }

        return sbHex.toString();
    }

}